<?php
namespace app\admin\controller;

use app\common\model\User;
use app\common\model\Chatroom as ChatroomModel;
use app\common\model\Chatroommessage as ChatroommessageModel;
use Firebase\JWT\JWT as JWTUtil;
use plug\SUtil;

class Chatroom extends Base
{
	public $type = 2;

	/**
	 * @route('chatroom/index')
	 * 轮播图列表
	 */
	public function index()
	{
		return $this->fetch('chatroom/index');
	}

	/**
	 * @route('chatroom/chatroomtoken','get')
	 * 获取进入聊天室的token
	 */
	public function chatroomtoken()
	{
		$user_id = input('user_id');
		$UserModel = new User();
		$User = $UserModel->where([
			'user_id'=>$user_id,
		])->find();
		if(!$User){
			$this->result([],-1,'用户存在异常');
		}

		$string = input('string');
		$key = md5(''); //jwt的签发密钥，验证token的时候需要用到
		$jwtAuth = json_encode(JWTUtil::decode($string,$key,['HS256']));
		$authInfo = json_decode($jwtAuth,true);

		$ChatroomModel = new ChatroomModel();
		$ChatroomId = $ChatroomModel->CreateChatRoom($this->_shopid,$user_id,$authInfo['client_id'],$this->type);
		if(!$ChatroomId){
			$this->result([],-1,'进入聊天室失败');
		}

		$token = SUtil::createjwt([
			'cm_id' => $ChatroomId,
			'shop_id' => $this->_shopid,
			'user_id' => $user_id,
			'client_id' => $authInfo['client_id'],
			'type' => $this->type,
		]);
		$this->result([
			'token' => $token,
			'cm_id' => $ChatroomId,
		],1,'操作成功');
	}

	/**
	 * @route('chatroom/chatroomtokenlist','get')
	 * 后台获取聊天列表
	 */
	public function chatroomtokenlist()
	{
		$limit = input('limit');
		$ChatroomModel = new ChatroomModel();
		$ChatroomList = $ChatroomModel->GetChatRoomList($this->type,$this->_shopid,$limit);
		$this->result($ChatroomList,1,'操作成功');
	}

	/**
	 * @route('chatroom/gethistoricaldata','get')
	 * 获取聊天室历史消息
	 */
	public function GetHistoricalData()
	{
		$limit = input('limit');
		$cm_id = input('cm_id');
		$ChatroommessageModel = new ChatroommessageModel();
		$ChatroomList = $ChatroommessageModel->GetHistoricalData($this->type,$cm_id,$this->_shopid,$limit);
		$this->result($ChatroomList,1,'操作成功');
	}
}
